import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../common/entity/message.dart';
import '../common/services/message_service.dart';

/// 消息状态类
class MessageState {
  final List<MessageEntity> messages;
  final List<MessageEntity> conversations;
  final Map<String, List<MessageEntity>> conversationCache;
  final bool isLoading;
  final String? error;
  final int unreadCount;

  const MessageState({
    this.messages = const [],
    this.conversations = const [],
    this.conversationCache = const {},
    this.isLoading = false,
    this.error,
    this.unreadCount = 0,
  });

  MessageState copyWith({
    List<MessageEntity>? messages,
    List<MessageEntity>? conversations,
    Map<String, List<MessageEntity>>? conversationCache,
    bool? isLoading,
    String? error,
    int? unreadCount,
  }) {
    return MessageState(
      messages: messages ?? this.messages,
      conversations: conversations ?? this.conversations,
      conversationCache: conversationCache ?? this.conversationCache,
      isLoading: isLoading ?? this.isLoading,
      error: error,
      unreadCount: unreadCount ?? this.unreadCount,
    );
  }
}

/// 消息状态管理器
class MessageNotifier extends StateNotifier<MessageState> {
  MessageNotifier() : super(const MessageState());

  /// 加载所有消息
  Future<void> loadAllMessages() async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final messages = MessageService.getAllMessages();
      state = state.copyWith(messages: messages, isLoading: false);
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Failed to load messages: $e',
      );
    }
  }

  /// 加载用户的对话列表
  Future<void> loadConversations(String userId) async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final conversations = MessageService.getLatestConversationsFiltered(
        userId,
      );
      final unreadCount = MessageService.getUnreadCount(userId);

      state = state.copyWith(
        conversations: conversations,
        unreadCount: unreadCount,
        isLoading: false,
      );
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Failed to load conversations: $e',
      );
    }
  }

  /// 加载两个用户之间的对话
  Future<void> loadConversation(String userId1, String userId2) async {
    final conversationKey = _getConversationKey(userId1, userId2);

    try {
      final messages = MessageService.getConversation(userId1, userId2);
      final updatedCache = Map<String, List<MessageEntity>>.from(
        state.conversationCache,
      );
      updatedCache[conversationKey] = messages;

      state = state.copyWith(conversationCache: updatedCache);
    } catch (e) {
      state = state.copyWith(error: 'Failed to load conversation: $e');
    }
  }

  /// 发送消息
  Future<bool> sendMessage({
    required String senderId,
    required String receiverId,
    required String content,
    required MessageType type,
  }) async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final success = await MessageService.sendMessage(
        senderId: senderId,
        receiverId: receiverId,
        content: content,
        type: type,
      );

      if (success) {
        // 重新加载相关数据
        await loadConversation(senderId, receiverId);
        await loadConversations(senderId);

        state = state.copyWith(isLoading: false);
        return true;
      } else {
        state = state.copyWith(
          isLoading: false,
          error: 'Failed to send message',
        );
        return false;
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: 'Failed to send message: $e',
      );
      return false;
    }
  }

  /// 标记消息为已读
  Future<bool> markAsRead(String messageId, String userId) async {
    try {
      final success = await MessageService.markAsRead(messageId);

      if (success) {
        // 更新未读消息数量
        final unreadCount = MessageService.getUnreadCount(userId);
        state = state.copyWith(unreadCount: unreadCount);

        // 重新加载对话列表
        await loadConversations(userId);
      }

      return success;
    } catch (e) {
      state = state.copyWith(error: 'Failed to mark message as read: $e');
      return false;
    }
  }

  /// 标记对话为已读
  Future<bool> markConversationAsRead(String userId, String partnerId) async {
    try {
      final success = await MessageService.markConversationAsRead(
        userId,
        partnerId,
      );

      if (success) {
        // 重新加载相关数据
        await loadConversation(userId, partnerId);
        await loadConversations(userId);

        // 更新未读消息数量
        final unreadCount = MessageService.getUnreadCount(userId);
        state = state.copyWith(unreadCount: unreadCount);
      }

      return success;
    } catch (e) {
      state = state.copyWith(error: 'Failed to mark conversation as read: $e');
      return false;
    }
  }

  /// 删除消息
  Future<bool> deleteMessage(String messageId, String userId) async {
    try {
      final success = await MessageService.deleteMessage(messageId);

      if (success) {
        // 重新加载数据
        await loadAllMessages();
        await loadConversations(userId);
      }

      return success;
    } catch (e) {
      state = state.copyWith(error: 'Failed to delete message: $e');
      return false;
    }
  }

  /// 删除对话
  Future<bool> deleteConversation(
    String userId1,
    String userId2,
    String currentUserId,
  ) async {
    try {
      final success = await MessageService.deleteConversation(userId1, userId2);

      if (success) {
        // 清除缓存
        final conversationKey = _getConversationKey(userId1, userId2);
        final updatedCache = Map<String, List<MessageEntity>>.from(
          state.conversationCache,
        );
        updatedCache.remove(conversationKey);

        // 重新加载数据
        await loadConversations(currentUserId);

        state = state.copyWith(conversationCache: updatedCache);
      }

      return success;
    } catch (e) {
      state = state.copyWith(error: 'Failed to delete conversation: $e');
      return false;
    }
  }

  /// 获取对话消息
  List<MessageEntity> getConversationMessages(String userId1, String userId2) {
    final conversationKey = _getConversationKey(userId1, userId2);
    return state.conversationCache[conversationKey] ?? [];
  }

  /// 更新未读消息数量
  Future<void> updateUnreadCount(String userId) async {
    try {
      final unreadCount = MessageService.getUnreadCount(userId);
      state = state.copyWith(unreadCount: unreadCount);
    } catch (e) {
      state = state.copyWith(error: 'Failed to update unread count: $e');
    }
  }

  /// 清除错误信息
  void clearError() {
    state = state.copyWith(error: null);
  }

  /// 生成对话缓存键
  String _getConversationKey(String userId1, String userId2) {
    final sortedIds = [userId1, userId2]..sort();
    return '${sortedIds[0]}_${sortedIds[1]}';
  }
}

/// 消息状态 Provider
final messageProvider = StateNotifierProvider<MessageNotifier, MessageState>(
  (ref) => MessageNotifier(),
);

/// 对话列表 Provider（便于访问）
final conversationsProvider = Provider<List<MessageEntity>>((ref) {
  return ref.watch(messageProvider).conversations;
});

/// 未读消息数量 Provider
final unreadCountProvider = Provider<int>((ref) {
  return ref.watch(messageProvider).unreadCount;
});

/// 特定对话消息 Provider
final conversationMessagesProvider =
    Provider.family<List<MessageEntity>, String>((ref, conversationKey) {
      final state = ref.watch(messageProvider);
      return state.conversationCache[conversationKey] ?? [];
    });
